<?php
/**
 * YBatchStorage.php
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @since 2.0
 */

Yii::import('common.components.batch.YBatchStorageInterface');

/**
 * Class BatchStorage
 */
class YBatchStorage extends CApplicationComponent implements YBatchStorageInterface {
	/**
	 * @var CDbConnection
	 */
	protected $db;

	public function init()
	{
		$this->db = Yii::app()->getDb();
		parent::init();
	}

	/**
	 * @param $id
	 * @return mixed
	 */
	public function load($id)
	{
		/** @var CSecurityManager $securityManager */
		$securityManager = Yii::app()->getSecurityManager();
		$batch = $this->db->createCommand()
			->select('batch')
			->from('{{batch}}')
			->where('bid=:bid AND token=:token', array(
				':bid' => $id,
				':token' => $securityManager->hashData($id)
			))->queryScalar();
		if ($batch) {
			return unserialize($batch);
		}
		return false;
	}

	/**
	 * @param array $batch
	 */
	public function create(array $batch)
	{
		/** @var CSecurityManager $securityManager */
		$securityManager = Yii::app()->getSecurityManager();
		$this->db->createCommand()->insert('{{batch}}', array(
			'bid' => $batch['id'],
			'timestamp' => $_SERVER['REQUEST_TIME'],
			'token' => $securityManager->hashData($batch['id']),
			'batch' => serialize($batch['batch'])
		));
	}

	/**
	 * @param array $batch
	 */
	public function update(array $batch)
	{
		$this->db->createCommand()->update('{{batch}}', array(
			'batch' => serialize($batch['batch'])
		), 'bid=:bid', array(':bid' => $batch['id']));
	}

	/**
	 * @param $id
	 */
	public function delete($id)
	{
		$this->db->createCommand()->delete('{{batch}}', 'bid=:bid', array(':bid' => $id));
	}

	/**
	 */
	public function cleanup()
	{
		$this->db->createCommand()->delete('{{batch}}', 'timestamp<:timestamp', array(
			':timestamp' => $_SERVER['REQUEST_TIME'] - 864000
		));
	}
}